//
//  ContentView.swift
//  Teacher
//
//  Created by qh w on 2021/5/3.
//

import SwiftUI
import AVFoundation
import CarBode
import ActivityKit
import CoreBluetooth
//import DashBoard

struct ContentView: View {
    @StateObject var UserData: CoreData
    @EnvironmentObject var ClassName: ClassNameData
    @State var errorStr = ""
    @State var showError = false
    @State var allowBLE: Bool = false
    @Binding var showWarning: Bool
    @State var isLoaded = false
    @State var showSetting = false
    @State var once = false
    @State var timeOut = 0
    @State var UIAController = UIAlertController()
    @State var timer = Timer.TimerPublisher(interval: 5, runLoop: .current,
                                            mode: .default).autoconnect()
    var body: some View {
        DispatchQueue.main.async {
            if !once {
                once = true
                connect()
            }
        }
        for idx in 0..<ClassName.ClassName.count {
            if UserData.classNameStr == ClassName.ClassName[idx].name && ClassName.ClassName[idx].BLEName != nil {
                DispatchQueue.main.async {
                    allowBLE = true
                }
                break
            }
        }
        return ZStack {
            VStack {
                if isLoaded {
                    ScrollView {
                        VStack(alignment: .leading) {
                            if UserData.events.count == 0 {
                                List {
                                    Text("暂无项目")
                                }
                            }
                            else {
                                ForEach(UserData.events) { _event in
                                    if _event.techer == UserDefaults(suiteName: "group.classmanager")!.string(forKey: "teacherName") && abs(Int((_event.start - Date().timeIntervalSince1970)/60)) <= 5
                                        && _event.state == -1
                                    {
                                        VStack {
                                            Text("最近日程:")
                                                .font(.title)
                                                .fontWeight(.bold)
                                                .padding(.leading)
                                            SingleEventView(_event: _event, allowBLE: $allowBLE, signable: true)
                                                .environmentObject(UserData)
                                                .environmentObject(ClassName)
                                        }
                                    }
                                }
                                Text("未签到:")
                                    .font(.title)
                                    .fontWeight(.bold)
                                    .padding(.leading)
                                ForEach(UserData.events) { _event in
                                    if _event.techer == UserDefaults(suiteName: "group.classmanager")!.string(forKey: "teacherName")
                                        && _event.state == -1
                                    {
                                        SingleEventView(_event: _event, allowBLE: $allowBLE, signable: true)
                                            .environmentObject(UserData)
                                            .environmentObject(ClassName)
                                    }
                                }
                                Text("其他:")
                                    .font(.title)
                                    .fontWeight(.bold)
                                    .padding(.leading)
                                ForEach(UserData.events) { _event in
                                    if _event.techer == UserDefaults(suiteName: "group.classmanager")!.string(forKey: "teacherName")
                                        && _event.state != -1
                                    {
                                        SingleEventView(_event: _event, allowBLE: $allowBLE, signable: false)
                                            .environmentObject(UserData)
                                            .environmentObject(ClassName)
                                    }
                                }
                            }
                        }
                        .navigationBarTitle("\(UserDefaults(suiteName: "group.classmanager")!.string(forKey: "teacherName") ?? "")的课表 - \(UserData.classNameStr)班")
                        .navigationBarItems(leading: HStack {
                            Button(action: {
                                self.showSetting = true
                            }) {
                                Image(systemName: "gearshape.fill")
                                    .imageScale(.large)
                            }
                            if allowBLE {
                                Divider()
                                Image(systemName: "wave.3.left.circle.fill")
                            }
                        })
                        .sheet(isPresented: self.$showSetting, content: {
                            NavigationView {
                                SettingsView(showCloseButton: true, showTeacherTextField: true)
                            }
                    })
                    }
                }
                else {
                    HStack {
                        Text("正在加载...")
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                    }
                }
            }
//            if showWarning {
//                IsUploadingWarning(showWarning: self.$showWarning)
//            }
        }
        .background(SUIAController(showAlert: $showError, $UIAController))
        .onReceive(timer, perform: { _ in
            // print(UserData.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG)
            self.showWarning = UserData.FILE_PROVIDER_IS_UPLOADING_FLAG
            if UserData.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG {
                timeOut += 1
            }
            if timeOut == 10 {
                timeOut = 0
                connect()
            }
            if !UserData.FILE_DOWNLOAD_ISNOT_FINISHED_FLAG {
                self.isLoaded = true
                connect()
                if let error = UserData.fileProviderError {
                    self.timer = Timer.TimerPublisher(interval: 120, runLoop: .current, mode: .default).autoconnect()
                    UserData.fileProviderError = nil
                    self.errorStr = error.localizedDescription + "\nPlease reopen the app or contact with your adiministrator for further help."
                    UIAController = UIAlertController(title: "网络错误", message: errorStr, preferredStyle: .alert)
                    UIAController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
                    UIAController.addAction(UIAlertAction(title: "重试", style: .destructive, handler: { _ in
                        self.timer = Timer.TimerPublisher(interval: 5, runLoop: .current, mode: .default).autoconnect()
                    }))
                    self.showError = true
                }
            }
        })
    }
    
    private func connect() {
        withAnimation(.easeInOut(duration: 0.5)) {
            if UserData.downloadDataByHttp() {}
            else {
                if let error = UserData.fileProviderError {
                    UserData.fileProviderError = nil
                    self.errorStr = error.localizedDescription
                    //                    self.showError = true
                }
            }
        }
    }
}

struct SingleEventView: View {
    @State var _event: event
    @Binding var allowBLE: Bool
    @EnvironmentObject var UserData: CoreData
    @EnvironmentObject var ClassName: ClassNameData
    @State var isPresented = false
    @State var signable: Bool
    var body: some View {
        if !_event.isRemoved {
            Fluent_Rect {
                VStack {
                    HStack {
                        Text(UserData.classes[_event._class].name)
                            .font(.title)
                        Spacer()
                        Text("任课老师:\(UserData.events[_event.id].techer)")
                            .font(.title)
                    }
                    Spacer()
                    HStack {
                        Text("始末时间:\(UserData.events[_event.id].start.string()) ~ \(UserData.events[_event.id].end.string())")
                        Spacer()
                    }
                    HStack {
                        Text("持续时间:\(Int((UserData.events[_event.id].end-UserData.events[_event.id].start)/60))分钟")
                        Spacer()
                        Text("状态:\(UserData.events[_event.id].state.convertToString())")
                    }
                    Divider()
                    Text(signable ? "提示：轻点卡片可以唤出签到扫码哦~":"当前不可扫码，请联系管理员！")
                        .foregroundColor(.gray)
                }
                .foregroundColor(.white)
                .padding(.all)
                .sheet(isPresented: self.$isPresented) {
                    CustomizedScannerView(_event: _event)
                        .environmentObject(UserData)
                        .environmentObject(ClassName)
                }
            }
            .onTapGesture {
                self.isPresented = signable
            }
            .frame(height: 170)
        }
    }
}

struct CustomizedScannerView: View {
    @Environment(\.presentationMode) var presentation
    @EnvironmentObject var UserData: CoreData
    @EnvironmentObject var ClassName: ClassNameData
    @State var _event: event
    @State var isFailed = false
    @State var UIAController = UIAlertController()
    @State var simulator = false
    @State var once = false
    @State var onceBLE = false
    @State var allowBLE = true
    @State var BLEProblem: String?
    @State var BLEName = ""
    @State var delegate: MyCBCentralManagerDelegate?
    @State var stopScan: (() -> Void)?
    var body: some View {
        
        //MARK: Detect Simulator Env
        #if(targetEnvironment(simulator))
        if !once {
            DispatchQueue.main.async {
                once = true
                simulator = true
            }
        }
        #endif
        
        if !onceBLE {
            for idx in 0..<ClassName.ClassName.count {
                if UserData.classNameStr == ClassName.ClassName[idx].name {
                    if ClassName.ClassName[idx].BLEName == nil {
                        DispatchQueue.main.async {
                            allowBLE = false
                        }
                    }
                    if let BLEName = ClassName.ClassName[idx].BLEName {
                        DispatchQueue.main.async {
                            self.BLEName = BLEName
                            self.delegate = MyCBCentralManagerDelegate(id: CBUUID(string: self.BLEName), BLEProblem: $BLEProblem, stopScan: { stopScan in
                                self.stopScan = stopScan
                            }, timeOutCompletion: {
                                UIAController = UIAlertController(title: "错误", message: "无有效签到设备", preferredStyle: .alert)
                                DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                                    presentation.wrappedValue.dismiss()
                                }
                                self.isFailed = true
                            }) {
                                if !(abs(Int((_event.start - Date().timeIntervalSince1970)/60)) <= 5) {
                                    UIAController = UIAlertController(title: "错误", message: "当前不在签到时间", preferredStyle: .alert)
                                    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                                        presentation.wrappedValue.dismiss()
                                    }
                                    self.isFailed = true
                                    return
                                }
                                
                                
                                //MARK: Request a Live Activity
                                let initialContentState = HomeScreenWidgetsAttributes.ContentState(remainingMinute: Date(timeIntervalSince1970: _event.start)...Date(timeIntervalSince1970: _event.end))
                                let activityAttributes = HomeScreenWidgetsAttributes(totalMinute: Int((_event.end-_event.start)/60), classTypeString: UserData.classes[_event._class].name, classString: UserData.classNameStr)
                                do {
                                    if #available(iOS 16.1, *) {
                                        let activity = try Activity.request(attributes: activityAttributes, contentState: initialContentState)
                                        Task {
                                            await activity.end(using: initialContentState, dismissalPolicy: .after(Date(timeIntervalSince1970: _event.end)))
                                        }
                                    } else {
                                        // Fallback on earlier versions
                                    }
                                    print("Requested a Live Activity.")
                                } catch (let error) {
                                    print("Error requesting a Live Activity \(error.localizedDescription).")
                                }
                                
                                showSuccess()
                            }
                        }
                    }
                }
            }
            DispatchQueue.main.async {
                onceBLE = true
            }
        }
        
        return NavigationView {
            VStack(spacing: 50) {
                if allowBLE {
                    Image(systemName: "wave.3.backward")
                        .resizable()
                        .scaledToFill()
                        .frame(width: 100, height: 100)
                        .padding()
                    Text("无线打卡")
                        .font(.title)
                    Text("无线打卡已启用，扫码打卡已禁用")
                }
                HStack {
                    Text(BLEProblem == nil ? (allowBLE ? "扫描蓝牙签到机...":"不支持蓝牙签到，请扫描二维码"):BLEProblem!)
                    if allowBLE {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                    }
                }
                if !allowBLE {
                    CBScanner(supportBarcode: .constant([.qr]), cameraPosition: .constant(.back), onFound: {
                        if $0.value == "\(Double(_event.start+_event.end))" || simulator {
                            
                            
                            
                            //MARK: Request a Live Activity
                            let initialContentState = HomeScreenWidgetsAttributes.ContentState(remainingMinute: Date(timeIntervalSince1970: _event.start)...Date(timeIntervalSince1970: _event.end))
                            let activityAttributes = HomeScreenWidgetsAttributes(totalMinute: Int((_event.end-_event.start)/60), classTypeString: UserData.classes[_event._class].name, classString: UserData.classNameStr)
                            do {
                                if #available(iOS 16.1, *) {
                                    let activity = try Activity.request(attributes: activityAttributes, contentState: initialContentState)
                                    Task {
                                        await activity.end(using: initialContentState, dismissalPolicy: .after(Date(timeIntervalSince1970: _event.end)))
                                    }
                                } else {
                                    // Fallback on earlier versions
                                }
                                print("Requested a Live Activity.")
                            } catch (let error) {
                                print("Error requesting a Live Activity \(error.localizedDescription).")
                            }
                            showSuccess()
                        }
                        else {
                            UIAController = UIAlertController(title: "错误", message: "二维码不正确", preferredStyle: .alert)
                            UIAController.addAction(UIAlertAction(title: "确定", style: .cancel))
                            self.isFailed = true
                        }
                        
                    }, onDraw: { _ in
                        
                    })
                }
            }
            .background(SUIAController(showAlert: $isFailed, $UIAController))
            .navigationTitle("签到")
            .toolbar(content: {
                ToolbarItem(placement: .navigationBarTrailing, content: {
                    Button(action: {
                        self.presentation.wrappedValue.dismiss()
                    }) {
                        Text("完成")
                    }
                })
            })
        }
        .onDisappear {
            stopScan?()
        }
    }
    
    private func showSuccess() {
        UIAController = UIAlertController(title: "签到成功", message: "课程实时活动将在锁屏界面", preferredStyle: .alert)
        isFailed = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            UserData.changeeventState(at: _event.id, to: .succeded)
        }
    }
}
